<template>
  <div class="app-container course">
    <div class="filter-container">
      <div class="filter-block">
        <span>标题：</span>
        <el-input size="small" maxlength="30"  v-model="listQuery.title" @keyup.enter.native="fetchData(true) "/>
      </div>

      <div class="filter-block">
        <span>创建时间：</span>
        <!--<el-input size="small"  @keyup.enter.native="fetchData(true)"/>-->
        <el-date-picker
          :picker-options="pickerOptionsBeginTime"
          @change="changeCreateBeginTime"
          style="margin-right: 10px"
          v-model="listQuery.createBeginTime"
          type="date"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择">
        </el-date-picker>
        至
        <el-date-picker
          :picker-options="pickerOptionsEndTime"
          @change="changeCreateEndTime"
          style="margin-left: 10px"
          size="small"
          v-model="listQuery.createEndTime"
          type="date"
          value-format="yyyy-MM-dd 23:59:59"
          placeholder="请选择">
        </el-date-picker>
      </div>

      <div class="filter-block">
        <span>学科：</span>
        <el-select clearable size="small" v-model="listQuery.checkedSubject" clearable @change="fetchData(true)" >
          <el-option v-for="item in subjectList" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId"/>
        </el-select>
      </div>

      <div class="filter-block">
        <span>学期：</span>
        <el-select clearable size="small"  clearable style="width: 220px" v-model="listQuery.checkedSemester" @change="handleChangeSemester()" >
          <el-option v-for="item in schoolSemesterList"
                     :key="item.code"
                     :label="item.label"
                     :value="item.code"/>
        </el-select>
      </div>
      <div class="filter-block">
        <span>年级：</span>
        <el-select clearable size="small" v-model="listQuery.checkedGrade" @change="handleCheckedGrade" >
          <el-option v-for="item in gradeTypeData" :key="item.distanceYear" :label="item.name" :value="item.distanceYear"/>
        </el-select>
      </div>
      <div class="filter-block" >
        <span>班级：</span>
        <el-select clearable size="small" v-model="listQuery.checkedClass"  @change="handleCheckedClass" >
          <el-option v-for="item in  classList" :key="item.classId" :label="item.className" :value="item.classId"/>
          <div style="height: 32px;line-height: 32px; text-align: center; color: #999999; font-size: 14px" slot="empty">请先选择年级</div>
        </el-select>
      </div>

      <div class="filter-btn-area">
        <el-button type="primary" size="small" @click="fetchData(true)">查询</el-button>
        <el-button type="none" size="small" @click="initListQuery">重置</el-button>
      </div>
      <div class="ope-btn-area">
        <!--<el-button size="primary" type="primary" @click="$router.push({path: '/personal/courseAdd'})">新增</el-button>-->
        <template v-if="permissions.indexOf('pl:personpostscript:export') !== -1">
          <el-button size="primary" type="none" class="btn-none" @click="exportPostscript"  >导出</el-button>
        </template>
      </div>
    </div>
    <div class="calc-area" style="font-size: 14px;margin-bottom: 5px;color: #909399">
      共计 <span style="color: #02b2b5">{{pageInfo.total}}</span>条备课记录
    </div>
    <el-table ref="form" :data="tableData"  border show-overflow-tooltip style="width: 100%">
      <el-table-column
        label="序号" align="center" type="index" width="50">
      </el-table-column>
      <el-table-column  label="学期" align="center">
        <template slot-scope="scope">
            <span  class="ellipsis2" :title=" formatSchoolYear(scope.row.schoolYear, scope.row.term)">
              {{ formatSchoolYear(scope.row.schoolYear, scope.row.term)}}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center" >
        <template slot-scope="scope">
          <span  class="ellipsis2" :title="scope.row.title">{{scope.row.title}}</span>
        </template>
      </el-table-column>

      <el-table-column label="关联备课" prop="title" align="center" >
        <template slot-scope="scope">
          <span  class="ellipsis2" :title="scope.row.lessonTitle">{{scope.row.lessonTitle}}</span>
        </template>
      </el-table-column>
      <el-table-column label="年级" prop="gradeName" align="center"/>
      <el-table-column label="班级" align="center" >
        <template slot-scope="scope">
          <span  class="ellipsis2" :title="formatClassName(scope.row.classNameStr)">{{formatClassName(scope.row.classNameStr)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="学科" prop="subjectName" align="center"/>
      <el-table-column label="创建人" prop="createName" align="center"/>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{scope.row.createAt | dataFormat }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        show-overflow-tooltip width="220" >
        <template slot-scope="scope">
          <div class="table-ope-btn-around">
            <el-link type="primary" :underline="false" @click="$router.push({path : '/postscript/postscriptDetail', query : {postscriptId : scope.row.id, lessonId : scope.row.lessonId}})">查看</el-link>

            <template v-if="permissions.indexOf('pl:personpostscript:addOrEdit') !== -1">
              <el-link type="primary" :underline="false" @click="$router.push({path: '/postscript/postscriptEdit', query:{postscriptId: scope.row.id, lessonId : scope.row.lessonId}})">编辑</el-link>
            </template>
            <template v-if="permissions.indexOf('pl:personpostscript:delete') !== -1">
              <template v-if="scope.row.canDelete == true">
                <el-link type="danger" :underline="false" @click="handleDeletePostscript(scope.row.id, scope.row.lessonId)">删除</el-link>
              </template>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.pageNum"
      :page-sizes="[10, 30 ,50]"
      :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>
    <el-confirm-dialog
      elTip="确定要删除当前记录吗？"
      :showDialog="cancelConfirm"
      :confirmSubmit="elConfirmDialogSubmit"
      :confirmCancel="elConfirmDialogCancel"
      @closeDialog = "elConfirmDialogClose"
    >
    </el-confirm-dialog>
  </div>
</template>

<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import {mapGetters} from 'vuex'
  import {getPostscriptList, getSubjectList,deletePersonalPostscript, getSchoolGradeList, getSchoolClassList, getSchoolSemesterList} from '@/api/api.js'
  export default {
        name: "postscriptList",
        computed: {
          ...mapGetters([
            'permissions'
          ])
        },
      components: {
        ElConfirmDialog
      },
        data() {
          return {
            exportUrl : process.env.VUE_APP_BASE_API + "/postscript/exportPerson",
            cancelConfirm : false,
            schoolId : sessionStorage.getItem("schoolId"),
            //学科列表
            subjectList : [],
            gradeTypeData: [],
            schoolSemesterList: [],
            //学期列表
            semesterList: [],
            //年级列表
            gradeList: [],
            //班级列表
            classList: [],
            //查询列表
            courseList : [],
            pickerOptionsBeginTime: {
              // disabledDate(time) {
              //   return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
              // }
            },
            pickerOptionsEndTime: {
              // disabledDate(time) {
              //   return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
              // }
            },
            pageInfo: {
              pageNum: 1,
              pageSize: 10,
              total: 0
            },
            listQuery : {
              title: '',
              createBeginTime: null,
              createEndTime: null,
              checkedSubject: '',
              checkedSemester: '',
              checkedGrade: '',
              checkedClass: '',
              distanceYear : '',
              schoolYear : '',
              term : '',
              currentSemester: {
                semesterId : '',
                schoolYear : '',
                term: '',
              },
            },
            //班级下拉是否可以使用
            classDisabled : true,
            tableData: [],
            currentPostscriptId : '', //当前操作的后记Id
            currentLessonId : '',// 当前操作的后记Id相关的备课Id
          }
        },
        methods: {
          /** 查询相关 **/
          fetchData(initPageInfo) {
            if (initPageInfo) {
              this.pageInfo.pageNum = 1;
            }

            let params = {
              pageNum: this.pageInfo.pageNum,
              pageSize: this.pageInfo.pageSize,
              title: this.listQuery.title,
              createStartTime: this.listQuery.createBeginTime,
              createEndTime: this.listQuery.createEndTime,
              subjectId: this.listQuery.checkedSubject,
              classId: this.listQuery.checkedClass,
              distanceYear: this.listQuery.checkedGrade,
              schoolYear: this.listQuery.currentSemester.schoolYear,
              term: this.listQuery.currentSemester.term,
              grade: this.listQuery.checkedGrade,
            }
            getPostscriptList(params).then(res => {
              if (res.code == 200) {
                this.tableData = (res.result && res.result.list && Array.isArray(res.result.list)) ? res.result.list : []
                this.pageInfo.total = res.result.total || 0
              } else {
                this.$alert("获取后记列表失败！" + res.message, "错误", {type: "error"})
              }
            })

          },
          //重置查询
          initListQuery() {
            this.classList = []
            this.listQuery = {
              title: '',
              createBeginTime: null,
              createEndTime: null,
              checkedSubject: '',
              checkedSemester: '',
              checkedGrade: '',
              checkedClass: '',
              distanceYear: '',
              schoolYear: '',
              term: '',
              currentSemester: {
                semesterId: '',
                schoolYear: '',
                term: '',
              },
            }
            this.pickerOptionsEndTime = {
              disabledDate(time) {
                return null;
              }
            }
            this.pickerOptionsBeginTime = {
              disabledDate(time) {
                return null;
              }
            }
            this.fetchData(true)
          },
          changeCreateBeginTime() {
            let createBeginTime = this.listQuery.createBeginTime
            if (createBeginTime) {
              let beginTime = new Date(createBeginTime.replace('-', '/'))
              this.pickerOptionsEndTime = {
                disabledDate(time) {
                  return time.getTime() < beginTime;
                }
              }
            } else {
              this.pickerOptionsEndTime = {
                disabledDate(time) {
                  return null;
                }
              }
            }
          },
          changeCreateEndTime() {
            let createEndTime = this.listQuery.createEndTime;
            if (createEndTime) {
              let endTime = new Date(createEndTime.replace('-', '/'))
              this.pickerOptionsBeginTime = {
                disabledDate(time) {
                  return time.getTime() > endTime;
                }
              }
            } else {
              this.pickerOptionsBeginTime = {
                disabledDate(time) {
                  return null;
                }
              }
            }

          },
          //选择年级变化后 ，班级相应变化
          handleCheckedGrade() {
            let distanceYear = this.listQuery.checkedGrade;
            if (isNaN(parseInt(this.listQuery.checkedGrade))) {
              this.classList = []
              this.listQuery.checkedClass = ''
              return
            }
            this.fetchData(true)
            let tempGrade = this.getGradeMsgByDistanceYear(this.listQuery.checkedGrade);
            if (tempGrade == null) {
              this.classList = []
              return;
            }
            let params = {
              grade: tempGrade.name,
              distanceYear: tempGrade.distanceYear
            }
            getSchoolClassList(params).then(res => {
              if (res.code == 200) {
                this.classList = res.result || []
              } else {
                this.$alert('学校还未维护该年级下班级信息，请联系华育技术支持进行初始化！', '提示', {
                  confirmButtonText: '我知道了',
                });
              }
            })
          },
          //切换班级
          handleCheckedClass(val) {
            if (val == true) {
              this.fetchData(true)
            }
          },
          /** 查询相关结束 **/
          /** 分页相关 **/
          handleSizeChange(val) {
            this.pageInfo.pageSize = val
            this.fetchData()
          },
          handleCurrentChange(val) {
            this.pageInfo.pageNum = val
            this.fetchData()
          },
          /** 分页相关结束**/
          /** 枚举格式化**/
          formatCourseType(code) {
            for (let item of this.courseList) {
              if (item.code === code) {
                return item.label;
              }
            }
            return "";
          },
          /** 枚举格式化结束**/

          /** 取消询问框相关**/
          elConfirmDialogSubmit() {
            this.cancelConfirm = false
            let params = {
              postscriptId: this.currentPostscriptId,
              lessonId: this.currentLessonId
            }
            deletePersonalPostscript(params).then(res => {
              if (res.code == 200) {
                this.$alert("删除成功！", "提示", {
                  type: "success",
                  callback: () => {
                    this.fetchData(true)
                  }
                })
              } else {
                this.$alert("删除失败！" + res.message, "错误", {type: "error"})
              }
            })
            this.cancelConfirm = false
          },
          elConfirmDialogCancel() {
            this.cancelConfirm = false
          },
          elConfirmDialogClose() {
            this.cancelConfirm = false
          },
          /** 取消询问框结束**/
          //点击删除
          handleDeletePostscript(id, lessonId) {
            if (!id || !lessonId) {
              return
            }
            this.currentPostscriptId = id;
            this.currentLessonId = lessonId;

            this.cancelConfirm = true
          },
          // 格式化学年信息
          formatSchoolYear(schoolYear, schoolTerm) {
            let year = parseInt(schoolYear) + parseInt(1)
            let term = schoolTerm == 1 ? "第一学期" : "第二学期"
            return `${schoolYear}年-${year}年${term}`
          },
          //格式化班级信息
          formatClassName(strArr) {
            if (strArr == undefined) {
              return
            }
            let classArr = strArr.split(",")
            let classNameStr = ""
            if (classArr.length > 0) {
              classArr.forEach(item => {
                classNameStr = classNameStr + `${item}班， `
              })
              let index = classNameStr.length - 2
              classNameStr = classNameStr.slice(0, index)
            }
            return classNameStr
          },
          /**  初始化 **/
          //初始化学科信息
          initSubjectList() {
            let params = {}
            getSubjectList(params).then(res => {
              if (res.code == 200) {
                this.subjectList = this.formatSubjectList(res.result)
              } else {
                this.$alert("获取学科数据失败！" + res.message, "错误", {type: "error"})
              }
            })
          },
          //格式化学科信息
          formatSubjectList(array) {
            if (!array || !Array.isArray(array) || array.length <= 0) {
              this.$alert('学校还未维护学科选项信息，请联系华育技术支持进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
              return []
            }
            let tempArr = []
            array.forEach(item => {
              let tempItem = {
                subjectId: item.id,
                subjectName: item.name,
                subjectCode: item.code,
                subjectType: item.type,
                subjectLevel: item.level
              }
              tempArr.push(tempItem)
            })
            return tempArr
          },
          //年级初始化
          initGradeList() {
            this.gradeTypeData = []
            getSchoolGradeList().then(res => {
              if (res.code === 200) {
                if (res.result && res.result.length && res.result.length > 0) {
                  this.gradeTypeData = res.result;
                } else {
                  this.$alert('学校还未维护年级选项信息，请联系华育技术支持进行初始化！', '提示', {
                    confirmButtonText: '我知道了',
                  });
                }
              } else {
                this.$alert("获取年级选项列表失败！" + res.message, "错误", {type: "error"})
              }
            })
          },
          // 根据年级distanceYear获取年级详情
          getGradeMsgByDistanceYear(code) {
            if (this.gradeTypeData && this.gradeTypeData.length && this.gradeTypeData.length > 0) {
              for (let item of this.gradeTypeData) {
                if (item.distanceYear == code) {
                  return item;
                }
              }
            }
            return null;
          },
          handleChangeSemester() {
            if (this.schoolSemesterList.length < 0) {
              return null
            }
            for (let item of this.schoolSemesterList) {
              if (item.code == this.listQuery.checkedSemester) {
                if (item.code.length >= 5) {
                  this.listQuery.currentSemester.semesterId = item.semesterId
                  this.listQuery.currentSemester.schoolYear = item.code.substr(0, 4)
                  this.listQuery.currentSemester.term = item.code.substr(4, 1)
                }
              }
            }
            this.fetchData(true)
          },
          initSchoolSemester() {
            getSchoolSemesterList().then(res => {
              if (res.code == 200) {
                if (res.result && Array.isArray(res.result) && res.result.length > 0) {
                  let tempSemesterList = res.result
                  tempSemesterList.forEach(semesterItem => {
                    let year = parseInt(semesterItem.schoolYear) + parseInt(1)
                    let term = semesterItem.term == 1 ? "第一学期" : "第二学期"
                    let label = `${parseInt(semesterItem.schoolYear)}年-${year}年${term}`
                    let code = `${semesterItem.schoolYear}${semesterItem.term}`
                    let semesterId = semesterItem.id
                    this.schoolSemesterList.push({label, code, semesterId})
                    this.schoolSemesterList.sort(this.compare('code'))
                  })
                } else {
                  this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                    confirmButtonText: '我知道了',
                  });
                }
              } else {
                this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
              }
            })

          },
          handleCheckedClass() {
            this.fetchData(true)
          },

          /**  初始化结束 **/
          //导出后记
          exportPostscript() {
            let url = this.exportUrl + "?schoolToken=" + sessionStorage.getItem("schoolId") + "&title=" + this.listQuery.title
              + "&createStartTime=" + this.listQuery.createBeginTime + "&createEndTime=" + this.listQuery.createEndTime
              + "&subjectId=" + this.listQuery.checkedSubject + "&classId=" + this.listQuery.checkedClass
              + "&distanceYear=" + this.listQuery.checkedGrade + "&schoolYear=" + this.listQuery.currentSemester.schoolYear
              + "&term=" + this.listQuery.currentSemester.term + "&grade=" + this.listQuery.checkedGrade
           console.log(url)
            window.open(url)
          },
          compare (propertyName) {
            return function (object1, object2) {
              let value1 = object1[propertyName]
              let value2 = object2[propertyName]
              if (value2 > value1) {
                return 1
              } else if (value2 < value1) {
                return -1
              } else {
                return 0
              }
            }
          }
        },
          created() {

          },
          mounted() {
            this.initSubjectList()
            this.initGradeList()
            this.initSchoolSemester()
            this.fetchData(true)
          }
      }
</script>
<style>
  .ellipsis2{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

  }
</style>
<style scoped lang="scss">

</style>
